package cs6238.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cs6238.common.Communication;
import cs6238.common.message.Message;

public class MockInputStream extends InputStream{

	byte[] message;
	int index;
	
	public MockInputStream(){
		message = null;
		index = 0;
	}
	
	@Override
	public int available(){
		if(message == null){
			return 0;
		}
		
		return message.length - index;
	}
 	     
	@Override
	public int read() throws IOException {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public int read(byte[] bytes){
		for(int i=0; i<bytes.length; i++){
			bytes[i] = message[index+i];
		}
		
		index += bytes.length;
		return 0;
	}
	
	private void setNext(byte[] nextSequence){
		if(message == null){
			message = nextSequence;
		}
		else{
			byte[] newMessage = new byte[message.length + nextSequence.length];
			for(int i=0; i<message.length; i++){
				newMessage[i] = message[i];
			}
			
			for(int i=0; i<nextSequence.length; i++){
				newMessage[i + message.length] = nextSequence[i];
			}
		
			message = newMessage;
		}
	}
	
	public void setNextByteMessage(byte[] bytes) throws IOException{
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		Communication.sendMessage(output, bytes);
		setNext(output.toByteArray());
	}
	
	public void setNextMessage(Message nextMessage) throws IOException{
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		Communication.sendMessage(output, nextMessage.serialize());
		setNext(output.toByteArray());
	}

}
